﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wwtfly.BBS.BackControllers.Attributes;
using System.Web.Mvc;
using Wwtfly.BBS.BackModels.ViewModels;
using Wwtfly.BBS.BackModels.Models.Home;
using Wwtfly.Utility;
using System.Security.Cryptography;
using Wwtfly.BBS.BackBLL.Users;
using Wwtfly.BBS.BackModels.Models.Users;
using Wwtfly.BBS.Enums.Users;
using System.Web.Security;
using System.Web;
using System.Web.Configuration;
using System.Configuration;
using Wwtfly.Extensions;
using Wwtfly.BBS.Enums.Common;
using Wwtfly.BBS.BackControllers.Common;

namespace Wwtfly.BBS.BackControllers.Home
{


    /// <summary>
    /// 后台 首页控制器
    /// </summary>
    [HasFolder("Back")]
    public class BackHomeController : BackBaseController
    {

        /// <summary>
        /// 随机码的 key值
        /// </summary>
        private static readonly string RandCodeKey = "RandCode";
        //
        public ActionResult Index()
        {
            return View();
        }

        //登陆
        public ActionResult Login()
        {
            LoginViewModel viewModel = new LoginViewModel();
            viewModel.Login = new LoginModel();
            viewModel.Login.ErrorMessage = (string)TempData["LoginErrorMessage"];
            viewModel.Login.UserName = (string)TempData["LoginUserName"];
            return View(viewModel);
        }


        // ajax 方式 获取 随机码
        public ActionResult GetRandCode()
        {
            string s = MethodHelper.RandomString(5);
            Session[RandCodeKey] = s;
            return this.Json(new { randCode = s }, JsonRequestBehavior.AllowGet);
        }

        //登陆验证
        [HttpPost]
        public ActionResult CheckLogin(LoginViewModel viewModel)
        {

            string errorMessage = null;
            string userName = null;
            if (viewModel != null && viewModel.Login != null)
            {
                viewModel.Login.UserName = userName = viewModel.Login.UserName ?? string.Empty;
                UsersModel model = UsersBLL.GetUsersInfo(viewModel.Login.UserName);
                if (model == null)
                {
                    errorMessage = "系统出错,请稍候再试!!";
                }
                else if (model.Id > 0)
                {
                    string randCodeKey=Convert.ToString(Session[RandCodeKey]);
                    randCodeKey = string.IsNullOrEmpty(randCodeKey) ? MethodHelper.RandomString(5) : randCodeKey;
                    string result = PasswordHelper.Md5((model.UserPassword + randCodeKey));
                    //判断密码是否相等
                    if (result.Equals(viewModel.Login.UserPassword))
                    {
                       /*判断用户,是否具有  后台 角色..*/
                        if (!HasBackRight(model))
                        {
                            errorMessage = "用户名或密码错误,请重试 !";
                        }
                        /*帐号被锁定 用户状态　　0代表用户可以登录 1代表禁用该用户*/
                        else if (model.UserState == UserStateEnum.UnLogin)
                        {
                            errorMessage = "帐号被锁定,请联系管理人员!";
                        }
                        else
                        {
                            //写入票据
                            AuthTicket(model);
                            //生成菜单

                            CreateMenu.CreateUAMenuInfo(model, ModuleTypeEnum.BACKBBS, Url, Server);
                            string returnUrl = Request.QueryString["ReturnUrl"];
                            if (string.IsNullOrEmpty(returnUrl))
                            {
                                return this.RedirectToAction("Index", "BackHome");
                            }
                            else
                            {
                                return this.Redirect(returnUrl);
                            }
                        }

                    }
                    else
                    {
                        errorMessage = "用户名或密码错误,请重试!";
                    }

                }
                else
                {
                    errorMessage = "用户名或密码错误,请重试!";
                }
            }
            TempData["LoginErrorMessage"] = errorMessage;
            TempData["LoginUserName"] = userName;
            return this.RedirectToAction("Login");
        }

        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();
            this.Session.Abandon();
            Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
            return RedirectToAction("Login");
        }


        //写入验证票据, 
        /// <summary>
        ///  写入验证票据, 
        /// </summary>
        /// <param name="user"></param>
        private void AuthTicket(UsersModel user)
        {
            Session[LoginUserUtil.LOGIN_USER] = user;//将用户 存入 session
            AuthenticationSection authentication =
                (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication");
            DateTime dt = DateTime.Now;
            FormsAuthenticationTicket fat = new FormsAuthenticationTicket(
                1, user.UserName, dt, dt.AddMinutes(
                    authentication.Forms.Timeout.TotalMinutes), false,
                string.Format("{0},{1},{2}",Request.GetRemoteIpAddress(), user.Id, user.UserName));
            string securityFat = FormsAuthentication.Encrypt(fat);
           
            HttpCookie hcLogin = new HttpCookie(FormsAuthentication.FormsCookieName) { Value = securityFat };
            this.Response.Cookies.Add(hcLogin);
        }


    }
}
